package it.sportingnola.soccernotes;

import it.sportingnola.soccernotes.adapter.TeamACAdapter;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

/**
 * Questa classe controlla l'attività di editing/creazione della cronaca
 * 
 * @author paolo
 */
public class NoteEdit extends AbstractSoccerActivity {
    private EditText titleText;
    private EditText notesText;
    private EditText dateText;
    private AutoCompleteTextView team1Text;
    private AutoCompleteTextView team2Text;
    private EditText assistentsText;
    private EditText corner1;
    private EditText corner2;
    private EditText foul1;
    private EditText foul2;
    private EditText refereeText;
    private EditText resultText;
    private EditText placeText;
    private Spinner playerNrSpinner;

    public void addCorner1(View view) {
	addOne(corner1);
    }

    public void addCorner2(View view) {
	addOne(corner2);
    }

    /**
     * Aggiungi un fallo alla squadra di casa
     * 
     * @param view
     */
    public void addFoul1(View view) {
	addOne(foul1);
    }

    /**
     * Aggiungi un fallo alla squadra in trasferta
     * 
     * @param view
     */
    public void addFoul2(View view) {
	addOne(foul2);
    }

    private void addOne(EditText et) {
	String txt=et.getText().toString();
	if ("".equals(txt)) {
	    et.setText("1");
	}
	else {
	    try {
		et.setText(Integer.toString(Integer.parseInt(txt) + 1));
	    }
	    catch (NumberFormatException e) {
		et.setText("1");
	    }
	}

    }

    @Override
    public void cancella(View view) {
	chiudi(null);
    }

    @Override
    public void chiudi(View view) {
	setResult(RESULT_OK);
	finish();
    }

    @Override
    public void doLeftSwipeAction() {
	editGoal(null);
    }

    @Override
    public void doRigthSwipeAction() {
	editAction(null);
    }

    /**
     * Apre la finestra di gestione della squadra di casa
     * 
     * @param view
     */
    public void editTeam1(View view) {
	if ( ! isTeam1Set()) {
	    return;
	}
	Intent i=new Intent(this, TeamEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, cronaca);
	i.putExtra(Const.Players.KEY_TEAM, Const.HOME_TEAM);
	i.putExtra(Const.Players.NAME, team1Text.getText().toString());
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, getNrPlayers());
	startActivityForResult(i, SoccerNotes.TEAM_EDIT);
    }

    /**
     * Apre la finestra di gestione della squadra in trasferta
     * 
     * @param view
     */
    public void editTeam2(View view) {
	if ( ! isTeam2Set()) {
	    return;
	}
	Intent i=new Intent(this, TeamEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, cronaca);
	i.putExtra(Const.Players.KEY_TEAM, Const.FOREIGN_TEAM);
	i.putExtra(Const.Players.NAME, team2Text.getText().toString());
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, getNrPlayers());
	startActivityForResult(i, SoccerNotes.TEAM_EDIT);
    }

    @Override
    protected void fillData() {
	if ((cronaca == null) || (0 == cronaca)) {
	    long id=dbHelper.createNote(getString(R.string.default_title), getString(R.string.default_notes), "0-0",
		getString(R.string.stadium), default_nr_players, 0, 0, 0, 0);
	    if (id > 0) {
		cronaca=id;
	    }
	}
	Cursor cc=dbHelper.recuperaCronaca(cronaca);
	startManagingCursor(cc);
	cc.moveToFirst();
	titleText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_TITLE)));
	notesText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_BODY)));
	dateText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_MATCH_DATE)));
	team1Text.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_TEAM1)));
	team2Text.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_TEAM2)));
	assistentsText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_ASSISTENTS)));
	refereeText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_REFEREE)));
	resultText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_RESULT)));
	corner1.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_CORNER1)));
	corner2.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_CORNER2)));
	foul1.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_FOUL1)));
	foul2.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_FOUL2)));
	placeText.setText(cc.getString(cc.getColumnIndex(Const.Cronache.KEY_PLACE)));
	playerNrSpinner.setSelection(cc.getInt(cc.getColumnIndex(Const.Cronache.KEY_PLAYER_NR)));
	playerNrSpinner.setEnabled("".equals(team1Text.getText().toString())
	    && "".equals(team2Text.getText().toString()) && ! dbHelper.areThereAnyPlayer(cronaca, Const.HOME_TEAM)
	    && ! dbHelper.areThereAnyPlayer(cronaca, Const.FOREIGN_TEAM));
    }

    public int getNrPlayers() {
	Resources res=getResources();
	return Integer.parseInt(res.getStringArray(R.array.player_numbers)[playerNrSpinner.getSelectedItemPosition()]);
    }

    /**
     * @return restituisce l'identificativo della cronaca su cui sto lavorando
     */
    public Long getRowId() {
	return cronaca;
    }

    @Override
    public CharSequence getTeam1Name() {
	return team1Text.getText();
    }

    @Override
    public CharSequence getTeam2Name() {
	return team2Text.getText();
    }

    protected boolean isTeam1Set() {
	if ("".equals(team1Text.toString().trim())) {
	    Toast toast=Toast.makeText(this, getString(R.string.team1_missing_error), Toast.LENGTH_SHORT);
	    toast.show();
	    return false;
	}
	return true;
    }

    private boolean isTeam2Set() {
	if ("".equals(team2Text.toString().trim())) {
	    Toast toast=Toast.makeText(this, getString(R.string.team2_missing_error), Toast.LENGTH_SHORT);
	    toast.show();
	    return false;
	}
	return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
	if ((cronaca == null) && (savedInstanceState != null)) {
	    cronaca=savedInstanceState.getLong(Const.Cronache.KEY_ROWID);
	}
	super.onCreate(savedInstanceState);
	// Create the adView
	AdView adView=new AdView(this, AdSize.BANNER, Const.MY_AD_UNIT_ID);
	// Lookup your LinearLayout assuming it’s been given
	// the attribute android:id="@+id/mainLayout"
	LinearLayout layout=(LinearLayout) findViewById(R.id.ads);
	// Add the adView to it
	layout.addView(adView);
	// Initiate a generic request to load it with an ad
	adView.loadAd(new AdRequest());
    }

    /**
     * Quando l'attività va in pausa bisogna salvare
     */
    @Override
    protected void onPause() {
	super.onPause();
	saveState();
    }

    /**
     * al resume recupera i campi
     */
    @Override
    protected void onResume() {
	super.onResume();
	fillData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
	super.onSaveInstanceState(outState);
	if (cronaca != null) {
	    outState.putLong(Const.Cronache.KEY_ROWID, cronaca);
	}
    }

    @Override
    protected void onStop() {
	super.onPause();
	saveState();
    }

    @Override
    protected void performSetContentView() {
	setContentView(R.layout.note_edit);
    }

    @Override
    protected void performSetTitle() {
	setTitle(getString(R.string.match));
    }

    /**
     * Inizializza i campi presenti nella View
     */
    @Override
    public void prepareFields() {
	titleText=(EditText) findViewById(R.id.title);
	notesText=(EditText) findViewById(R.id.body);
	dateText=(EditText) findViewById(R.id.match_date);
	assistentsText=(EditText) findViewById(R.id.assistents);
	refereeText=(EditText) findViewById(R.id.referee);
	resultText=(EditText) findViewById(R.id.result);
	placeText=(EditText) findViewById(R.id.place);
	corner1=(EditText) findViewById(R.id.corner1);
	corner2=(EditText) findViewById(R.id.corner2);
	foul1=(EditText) findViewById(R.id.foul1);
	foul2=(EditText) findViewById(R.id.foul2);
	TeamACAdapter adapter=new TeamACAdapter(this, android.R.layout.simple_spinner_dropdown_item, dbHelper);
	team1Text=(AutoCompleteTextView) findViewById(R.id.team1);
	team2Text=(AutoCompleteTextView) findViewById(R.id.team2);
	team1Text.setAdapter(adapter);
	team2Text.setAdapter(adapter);
	playerNrSpinner=(Spinner) findViewById(R.id.nr_players);
	ArrayAdapter<CharSequence> plNrAdapter=ArrayAdapter.createFromResource(this, R.array.player_numbers,
	    android.R.layout.simple_spinner_dropdown_item);
	playerNrSpinner.setAdapter(plNrAdapter);
    }

    @Override
    protected void resetField() {
    }

    @Override
    public void salva(View view) {
	saveState();
	Toast toast=Toast.makeText(this, getString(R.string.just_saved), Toast.LENGTH_LONG);
	toast.show();
    }

    @Override
    public void saveState() {
	String title=titleText.getText().toString();
	String notes=notesText.getText().toString();
	String date=dateText.getText().toString();
	String team1=team1Text.getText().toString();
	String team2=team2Text.getText().toString();
	String assistents=assistentsText.getText().toString();
	String referee=refereeText.getText().toString();
	String result=resultText.getText().toString();
	String place=placeText.getText().toString();
	Long nrPlayers=playerNrSpinner.getSelectedItemId();
	int c1="".equals(corner1.getText().toString()) ? 0 : Integer.parseInt(corner1.getText().toString());
	int c2="".equals(corner2.getText().toString()) ? 0 : Integer.parseInt(corner2.getText().toString());
	int f1="".equals(foul1.getText().toString()) ? 0 : Integer.parseInt(foul1.getText().toString());
	int f2="".equals(foul2.getText().toString()) ? 0 : Integer.parseInt(foul2.getText().toString());
	dbHelper.updateNote(cronaca, title, notes, date, team1, team2, assistents, referee, result, place, nrPlayers,
	    c1, c2, f1, f2);
    }

    public void subCorner1(View view) {
	subOne(corner1);
    }

    public void subCorner2(View view) {
	subOne(corner2);
    }

    public void subFoul1(View view) {
	subOne(foul1);
    }

    public void subFoul2(View view) {
	subOne(foul2);
    }

    private void subOne(EditText et) {
	String txt=et.getText().toString();
	if ("".equals(txt) || "0".equals(txt)) {
	    et.setText("0");
	}
	else {
	    try {
		et.setText(Integer.toString(Integer.parseInt(txt) - 1));
	    }
	    catch (NumberFormatException e) {
		et.setText("0");
	    }
	}
    }

}
